<?php


namespace App\Services;


use App\Models\UserIp;
use App\Models\UserAccount;
use App\Models\User;
use App\Utils\Code;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;

class UserAuthService extends BaseService
{
    public function authIp(array $params) {
        $rules = [
            'user_id' => ['bail', 'required', 'integer', 'gte:1'],
            'ip_ids' => ['bail', 'nullable', 'array']
        ];
        $validator = Validator::make($params, $rules, [], [
            'user_id' => '用户主键',
            'ip_ids' => 'IP主键数据集'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        if (User::where('id', $params['user_id'])->doesntExist()) {
            throw new \Exception('用户信息不存在', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params) {
            UserIp::where('user_id', $params['user_id'])->delete();
            if ($params['ip_ids']) {
                $data = [];
                foreach ($params['ip_ids'] as $item) {
                    $data[] = [
                        'user_id' => $params['user_id'],
                        'ip_id' => $item
                    ];
                }
                return UserIp::insert($data);
            }
            return true;
        });
    }

    public function authAccount(array $params) {
        $rules = [
            'user_id' => ['bail', 'required', 'integer', 'gte:1'],
            'account_ids' => ['bail', 'nullable', 'array']
        ];
        $validator = Validator::make($params, $rules, [], [
            'user_id' => '用户主键',
            'account_ids' => '账号主键数据集'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        if (User::where('id', $params['user_id'])->doesntExist()) {
            throw new \Exception('用户信息不存在', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params) {
            UserAccount::where('user_id', $params['user_id'])->delete();
            if ($params['account_ids']) {
                $data = [];
                foreach ($params['account_ids'] as $item) {
                    $data[] = [
                        'user_id' => $params['user_id'],
                        'account_id' => $item
                    ];
                }
                return UserAccount::insert($data);
            }
            return true;
        });
    }
}
